<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;
use DB;

class Category extends Model
{
    protected $table = 'category';

    protected $primaryKey = 'id';
    public $timestamps = false;
    protected $guarded = [];

    //获取一条
    public function getListOne(){

        $where['status'] = 1;
        $where['depth'] = 1;
        $data = $this->where($where)->orderBy('menu_sort', 'asc')->get()->toArray();

        return $data;

    }
    //获取全部菜单
    public function getList(){

        $data['status'] = 1;
        $data = $this->where($data)->orderBy('sort', 'asc')->get()->toArray();

        $rs = $this->treeRoute($data);

        return $rs;
    }

    /*
     *     elm-ui 分类列表
     *     id:1,
     *     name:'新闻中心',
     *     children:[
     */
    public function  treeRoute(array $data,int $pid=0,int $deep=0) : array
    {
        $tree=[];
        foreach ($data as $row) {
            if($row['parent_id'] == $pid){
                $row['deep'] = $deep;
                $row['label'] = $row['name'];
                $row['value'] = $row['id'];

                $row['children'] = $this->treeRoute($data,$row['id'],$deep+1);
                if($row['children'] == null){
                    //如果子元素为空则unset()进行删除，说明已经到该分支的最后一个元素了（可选）
                    unset($row['children']);
                }
                $tree[] = $row;
            }
        }
        return $tree;
    }




    //引用 分类排序
    function createNodeTree(&$list,&$tree){
        foreach($list as $key=>$node){
            if(isset($list[$node['pid']])){
                $list[$node['pid']]['children'][] = &$list[$key];
            }else{
                $tree[] = &$list[$node['id']];
            }
        }
    }



    // 得到父级栏目的等级
    public function getParentLevel($pid){
        if($pid  == 0){
            return 1;
        }else{
            $pLevel = $this->where('id',$pid)->pluck('level');
            return $pLevel[0]+1;
        }
    }









}
